<!-- templates/mqtt_monitor.html -->
<!DOCTYPE html>
<html>
<head>
    <title>MQTT Monitor</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        .container { max-width: 1200px; margin: 0 auto; }
        .status { padding: 10px; margin: 10px 0; border-radius: 5px; }
        .connected { background-color: #d4edda; color: #155724; }
        .disconnected { background-color: #f8d7da; color: #721c24; }
        .message { border: 1px solid #ddd; padding: 10px; margin: 5px 0; border-radius: 5px; }
        .message-topic { font-weight: bold; color: #007bff; }
        .message-payload { margin: 5px 0; }
        .message-meta { font-size: 0.8em; color: #666; }
        .publish-form { background: #f8f9fa; padding: 15px; border-radius: 5px; margin: 20px 0; }
        .publish-form input, .publish-form button { margin: 5px; padding: 8px; }
        .publish-form button { background: #007bff; color: white; border: none; border-radius: 3px; cursor: pointer; }
        #messages { max-height: 600px; overflow-y: auto; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 MQTT Monitor</h1>

        <div id="status" class="status disconnected">
            ❌ Disconnected
        </div>

        <div class="publish-form">
            <h3>📤 Publish Message</h3>
            <input type="text" id="topic" placeholder="Topic (e.g., name)" style="width: 200px;">
            <input type="text" id="message" placeholder="Message" style="width: 300px;">
            <button onclick="publishMessage()">Send</button>
        </div>

        <!-- 新增控制按钮 -->
        <div class="publish-form">
            <h3>🕹️ 控制</h3>
            <button onclick="sendControl('1')">前进</button>
            <button onclick="sendControl('2')">后退</button>
            <button onclick="sendControl('3')">左转</button>
            <button onclick="sendControl('4')">右转</button>
            <button onclick="sendControl('5')">停止</button>
        </div>

        <!-- 速度调节条 -->
        <div class="publish-form">
            <h3>🚗 速度调节</h3>
            <input type="range" id="speedRange" min="0" max="100" value="0" oninput="updateSpeedLabel(this.value)" onchange="sendSpeed(this.value)">
            <span id="speedLabel">0</span>
        </div>

        <div>
            <h3>📨 Messages <span id="message-count">(0)</span></h3>
            <button onclick="clearMessages()">Clear</button>
            <div id="messages"></div>
        </div>
    </div>

    <script>
        const socket = io();
        let messageCount = 0;

        socket.on('mqtt_status', function(data) {
            const statusDiv = document.getElementById('status');
            if (data.status === 'connected') {
                statusDiv.className = 'status connected';
                statusDiv.innerHTML = '✅ Connected to MQTT Broker';
            } else {
                statusDiv.className = 'status disconnected';
                statusDiv.innerHTML = '❌ Disconnected from MQTT Broker';
            }
        });

        socket.on('new_message', function(data) {
            displayMessage(data);
            if (data.topic === 'speed') {
                let val = parseInt(data.payload);
                if (!isNaN(val)) {
                    document.getElementById('speedRange').value = val;
                    updateSpeedLabel(val);
                }
            }
        });

        function displayMessage(data) {
            const messagesDiv = document.getElementById('messages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message';

            const timestamp = new Date(data.timestamp).toLocaleString();

            messageDiv.innerHTML = `
                <div class="message-topic">📍 Topic: ${data.topic}</div>
                <div class="message-payload">📝 ${data.payload}</div>
                <div class="message-meta">
                    🕒 ${timestamp} | QoS: ${data.qos} | Retained: ${data.retained}
                </div>
            `;

            messagesDiv.insertBefore(messageDiv, messagesDiv.firstChild);

            messageCount++;
            document.getElementById('message-count').textContent = `(${messageCount})`;
        }

        function publishMessage() {
            const topic = document.getElementById('topic').value;
            const message = document.getElementById('message').value;

            if (!topic || !message) {
                alert('Please enter both topic and message');
                return;
            }

            fetch('/api/publish', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    topic: topic,
                    message: message
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('message').value = '';
                    console.log('Message published successfully');
                } else {
                    alert('Failed to publish message');
                }
            });
        }

        function sendControl(cmd) {
            fetch('/api/publish', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    topic: 'name',
                    message: cmd
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status !== 'success') {
                    alert('Failed to send control command');
                }
            });
        }

        // 速度条相关
        function updateSpeedLabel(val) {
            document.getElementById('speedLabel').textContent = val;
        }
        function sendSpeed(val) {
            fetch('/api/publish', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    topic: 'speed',
                    message: val
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.status !== 'success') {
                    alert('Failed to set speed');
                }
            });
        }

        function clearMessages() {
            document.getElementById('messages').innerHTML = '';
            messageCount = 0;
            document.getElementById('message-count').textContent = '(0)';
        }

        // 加载历史消息
        fetch('/api/messages')
            .then(response => response.json())
            .then(messages => {
                messages.forEach(message => {
                    displayMessage(message);
                });
            });
    </script>
</body>
</html>